package pers.hl.library.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import pers.hl.library.common.base.BaseService;
import pers.hl.library.dao.BookBorRecMapper;
import pers.hl.library.po.BookBorRec;
import pers.hl.library.po.BookBorRecExample;

import java.util.Date;
import java.util.List;

/**
 * 书籍借阅记录
 */
@Service
public class BookBorRecordService extends BaseService<BookBorRec, BookBorRecExample> {

    @Autowired
    BookBorRecMapper mapper;

    public BookBorRecordService(BookBorRecMapper mapper) {
        init(mapper);
    }

    @Override
    public BookBorRec getDataByPrimaryId(Integer id) {
        return dao.selectByPrimaryKey(id);
    }

    @Override
    public boolean addData(BookBorRec data) {
        return mapper.insertSelective(data) > 0;
    }

    @Override
    public boolean batchAdd(List<BookBorRec> list) {
        return false;
    }

    @Override
    public boolean deleteData(Integer id) {
        return false;
    }

    @Override
    public boolean batchDelete(List<Integer> ids) {
        return false;
    }

    @Override
    public boolean update(BookBorRec data) {
        return false;
    }

    /**
     * 修改借阅记录状态
     *
     * @param recordId 借阅记录id
     * @param status   借阅状态
     * @return
     */
    public boolean updateStatus(Integer recordId, int status) {
        BookBorRec rec = new BookBorRec();
        rec.setBbrStatus(status);
        rec.setReturnTime(new Date());
        mExample = createExample();
        mExample.createCriteria().andBbrIdEqualTo(recordId);
        return updateByExampleSelective(rec);
    }

    /***
     * 根据bookId、借阅人id及状态(借阅中)查询当前书籍正在借阅中的记录
     */
    public BookBorRec getBorrowingRecord(Integer userId, Integer bookId) {
        mExample = createExample();
        mExample.createCriteria().andBbrBookIdEqualTo(bookId)
                .andBbrBorrowerEqualTo(userId)
                .andBbrStatusEqualTo(BookBorRec.STATUS_BORROWING);
        List<BookBorRec> list = mapper.selectByExample(mExample);
        if (ObjectUtils.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }

    public List<BookBorRec> getExpiringRecords(Integer userId) {
        return mapper.getExpiringRecords(userId);
    }
}
